//
//  HContactController.m
//  NursingManages
//
//  Created by HuangZhen on 2017/5/25.
//  Copyright © 2017年 huangzhen. All rights reserved.
//

#import <Foundation/Foundation.h>

#import "HContactViewController.h"
#import "HContactDetailViewController.h"
#import "DBHelper.h"
#import "TableEmployee.h"



@interface HContactViewController ()


@end



@implementation HContactViewController



-(NSMutableArray*) GetArrByFirstChar:(NSString*) firstChar{
    NSMutableArray* arr =[self.dataSourceFilterByFirstChar objectForKey:firstChar];
    return arr;
}

-(NSMutableArray*) GetArrBySectionNumber:(NSInteger) section {
    
    NSArray *sortArray = [self.dataSourceFilterByFirstChar.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    NSMutableArray* arr =[self.dataSourceFilterByFirstChar objectForKey:sortArray[section]];
    return arr;
}

- (NSArray *) escArray:(NSArray *)array{
    NSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    return sortArray;
}

- (instancetype)init{
    if (self) {
        [self refreshContactsData];
    }
    return self;
}

-(void)refreshContactsData{
    self.dataSourceFilterByFirstChar = [NSMutableDictionary new];
    self.dataSource = [[[TableEmployee alloc]init] GetEmpolyee];
    [self DealDataSource];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.barTintColor = kNavBlueColor;
    self.navigationController.navigationBar.titleTextAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]};

    self.mySearchBar =  [[UISearchBar alloc] initWithFrame:CGRectMake(0, NavBarHeight, ScreenWidth, 40)];
    self.mySearchBar.placeholder  = @"按首字母搜索";
    self.mySearchBar.delegate=self;
    
    self.refresh = [[UIRefreshControl alloc]initWithFrame:CGRectMake(0, NavBarHeight + 40, ScreenWidth , ScreenHeight - NavBarHeight - 40)];
    self.refresh.tintColor = [UIColor lightGrayColor];
    self.refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"下拉刷新"];
    [self.refresh addTarget:  self action:@selector(refreshTableviewAction:) forControlEvents:UIControlEventValueChanged];
    [self.myTableView addSubview:self.refresh];

    [self.view addSubview:self.mySearchBar];
    [self.view addSubview:self.myTableView];
}

- (UITableView *)myTableView
{
    if (!_myTableView) {
        _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, NavBarHeight + 40, ScreenWidth , ScreenHeight - NavBarHeight - 90) style: UITableViewStylePlain];
        _myTableView.dataSource = self;
        _myTableView.delegate = self;
        _myTableView.tableFooterView = [[UIView alloc]init];
        [_myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        // _myTableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    }
    return _myTableView;
}


- (void) DealDataSource {
    
    for (Model_Pub_Employee* model in self.dataSource) {
        NSString* firstChar = [model.INPUT_CODE1 substringToIndex:1];
        NSArray *array = [self escArray:self.dataSourceFilterByFirstChar.allKeys];
        if( [array containsObject: firstChar] ){
            NSMutableArray* arr =[self.dataSourceFilterByFirstChar objectForKey:firstChar];
            [arr addObject:model];
            [self.dataSourceFilterByFirstChar setObject:arr forKey:firstChar];
            
        }else{
            NSMutableArray* arr = [NSMutableArray new];
            [arr addObject:model];
            [self.dataSourceFilterByFirstChar setObject:arr forKey:firstChar];
            
        }
    }
}

#pragma mark 下拉刷新

-(void)refreshTableviewAction:(UIRefreshControl *)refreshs
{
    if (self.refresh.refreshing) {
        self.refresh.attributedTitle = [[NSAttributedString alloc]initWithString:@"正在刷新"];
        [self performSelector:@selector(refershData) withObject:nil afterDelay:2];
    }
}

-(void)refershData
{
    
    NSString *syseTiem = nil;
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //创建的时间格式
    syseTiem = [formatter stringFromDate:[NSDate date]];
    
    NSString *lastUpdated = [NSString stringWithFormat:@"上一次更新时间为 %@", [formatter stringFromDate:[NSDate date]]];
    
    self.refresh.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdated] ;

    [self.refresh endRefreshing];
    [self refreshContactsData];
    [self.myTableView reloadData];
}

#pragma mark 委托事件 UISearchBar

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchetxt
{
    self.dataSourceFilterByFirstChar = [NSMutableDictionary new];

    self.dataSource = [[[TableEmployee alloc]init] GetEmpolyeeWithInputCode:searchetxt];
    [self DealDataSource];
    
    [self.myTableView reloadData];
    
    if ( [ searchetxt isEqualToString: @"" ]){
        [self.mySearchBar resignFirstResponder];
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.mySearchBar resignFirstResponder];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [self.mySearchBar resignFirstResponder];
}



#pragma mark  委托  UITableView


-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    NSArray *array = [self escArray:[self.dataSourceFilterByFirstChar allKeys]];
    return array;
}

-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    return index;
}


- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSArray *array = [self escArray:[self.dataSourceFilterByFirstChar allKeys]];
    return array[section];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [self.dataSourceFilterByFirstChar allKeys].count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self GetArrBySectionNumber:section].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"cell";
    UITableViewCell *cell = [self.myTableView dequeueReusableCellWithIdentifier:cellID];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }
    
    NSArray *arresc = [self escArray:self.dataSourceFilterByFirstChar.allKeys];
    NSMutableArray* arr = [self.dataSourceFilterByFirstChar objectForKey:arresc[indexPath.section]];
    
    Model_Pub_Employee *model = arr[indexPath.row];
    [cell.textLabel setText:[NSString stringWithFormat:@"%@",model.EMP_NAME]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    NSMutableArray* arr = [self GetArrBySectionNumber:indexPath.section];
    Model_Pub_Employee *model = arr[indexPath.row];
    
    HContactDetailViewController *HMailVC = [[HContactDetailViewController alloc]initWithModel:model];
    HMailVC.hidesBottomBarWhenPushed = YES;
    
    
    [self.navigationController pushViewController:HMailVC animated:YES];
}

@end
